<template>
    <div>
        <ShareDataTable
            v-model:table-data="tableData"
            row-key="cntr"
            :table-columns="tableColumns"
            :table-attribute="tableAttribute"
            ref="childRef"
        >
        </ShareDataTable>
        <el-button-group class="bg">
            <el-space>
                <AddBtn @click="handleAdd" :formData="paramData"></AddBtn>
                <DelBtn @click="handleDelete"></DelBtn>
            </el-space>
        </el-button-group>
    </div>
    <div>
        <el-dialog
            v-model="dialogAddCntrsVisible"
            title="新增箱号"
            draggable
            destroy-on-close
        >
            <CntrTextArea @save="onAdded"></CntrTextArea>
        </el-dialog>
        <el-dialog
            v-model="dialogUpdateVisible"
            title="箱号维护"
            draggable
            destroy-on-close
            :center="true"
        >
            <NormalForm
                :formOptions="formOptions"
                :formItems="formItems"
                :rules="rules"
                :form-data="paramData"
                :createActionName="createActionName"
                :updateActionName="updateActionName"
                @create="onAdded"
                @close="onCloseDialog"
            >
            </NormalForm>
        </el-dialog>
    </div>
</template>
<script setup lang="ts" name="ContractCntrs">
import { ContractCntrModel } from '@/common/types/transpost.js';
import { ref, reactive, onMounted } from 'vue';
import ShareDataTable from '@/components/tables/ShareDataTable.vue';
import { tableColumnDefault } from '@/hooks/useTable.js';
import { FormFieldItem, TableColumn } from '@/common/types/app.js';
import { Request } from '@/app/request.js';
import {
    pickFormFromTable,
    validateCntr,
    validateCntrFunc,
} from '@/common/tools.js';
import { ElMessage, ElMessageBox, FormRules } from 'element-plus';
import CntrTextArea from '@/views/container/plan/CntrTextArea.vue';
import { forEach, forEachRight, includes } from 'lodash';

const tableData = defineModel<Array<ContractCntrModel>>('tableData');
const contractCntrSumId = defineModel<number | undefined>('contractCntrSumId', {
    default: undefined,
});
const childRef = ref<InstanceType<typeof ShareDataTable>>();

const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'cntr',
        label: '箱号',
        sortable: true,
        width: 150,
    },
]);
const paramData = ref<ContractCntrModel>({});
const createActionName = ref('委托箱号增加');
const updateActionName = ref('委托箱号修改');
const dialogAddCntrsVisible = ref(false);
const dialogUpdateVisible = ref(false);
const tableAttribute = ref({
    id: 'Contract-table-contractcntrs',
    height: 400,
});
const formOptions = reactive<{
    labelWidth?: string;
    labelPosition?: string;
}>({});
const formItems = reactive<Array<FormFieldItem>>(
    pickFormFromTable(tableColumns),
);

const rules = reactive<FormRules>({
    cntr: [
        { required: true, message: '箱号不能空', trigger: 'blur' },
        { validator: validateCntr, trigger: 'blur' },
    ],
});
const handleAdd = () => {
    // initObjectProperty(paramData.value);
    if (contractCntrSumId.value) {
        dialogAddCntrsVisible.value = true;
    } else {
        ElMessage.info({
            message: '请先选择箱型',
        });
    }
};

const onAdded = async (cntrs: string) => {
    if (!contractCntrSumId.value) {
        ElMessage.info({
            message: '请先选择箱型',
        });
        return;
    }
    // 更准确的分隔符处理，过滤空值
    const cntrArray = cntrs.split(/[,\n\s]+/).filter(Boolean);
    if (!tableData.value || cntrArray.length === 0) return;

    const tempData = [];
    const duplicateCntrs = [];
    const invalidCntrs = [];

    for (const cntr of cntrArray.map((c) => c.trim().toUpperCase())) {
        if (tableData.value.some((e) => e.cntr === cntr)) {
            duplicateCntrs.push(cntr);
            continue;
        }

        if (validateCntrFunc(cntr)) {
            tempData.push(cntr);
        } else {
            invalidCntrs.push(cntr);
        }
    }
    // 批量显示提示信息
    if (duplicateCntrs.length > 0) {
        ElMessage.info(`重复箱号: ${duplicateCntrs.join(', ')}`);
        return;
    }
    if (invalidCntrs.length > 0) {
        ElMessage.info(`非法箱号: ${invalidCntrs.join(', ')}`);
        return;
    }
    // 批量添加新数据（使用push+reverse代替unshift）

    if (tempData.length > 0) {
        const req = new Request(
            '委托箱号增加',
            {
                contract_cntr_sum_id: contractCntrSumId.value,
                cntrs: tempData,
            },
        );
        const r = await req.post();
        if (r.code > 100) {
            tableData.value.length = 0;
            tableData.value = r.obj;
        }
    }
    dialogAddCntrsVisible.value = false;
    
};
const handleDelete = async () => {
    const rows: Array<ContractCntrModel> =
        childRef.value?.tableRef?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return;
    }
    const ids = Array<number>();

    forEach(rows, (v: ContractCntrModel) => {
        ids.push(v.id as number);
    });

    const msg = '';
    const cr = await ElMessageBox.confirm(msg, '确认删除选中箱号', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('委托箱号删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(tableData.value, (v: ContractCntrModel, i: number) => {
                if (includes(ids, v.id)) {
                    tableData.value?.splice(i, 1);
                }
            });
        }
    }
};


const onCloseDialog = async (arg?: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
    if (dialogAddCntrsVisible.value) {
        dialogAddCntrsVisible.value = false;
    }
};

</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}
</style>
